package com.yu.task.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadUtils {
    //文件存放目标路径
    private static final  String BASE_PATH=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img";
    //定义访问图片的路径
    private static final String SERVER_PATH="http://localhost:8088/img/";

    public static String upload(MultipartFile file){
        //获得上传的名称
        String fileName = file.getOriginalFilename();
        //用户uuid替换原名
        String uuid = UUID.randomUUID().toString().replace("-","");
        //把uuid和文件名拼接
        String newFileName = uuid+"-"+fileName;

        File image = new File(BASE_PATH,newFileName);
        //创建文件夹
        if(!image.exists()){
            image.mkdir();
        }
        try{
            file.transferTo(image);
        }catch (IOException e){
            e.printStackTrace();
        }

        return  SERVER_PATH+newFileName;
    }
}

